<template>
  <!-- 身份认证 -->
  <div>
    <van-nav-bar
      left-arrow
      :title="$t('wallet.identity')"
      @click-left="router.back()"
    />
    <van-notice-bar
      left-icon="warning-o"
      background="#FFC1CF"
      color="#DE5D7A "
      :text="$t('wallet.warin')"
    />
    <div class="app-pad identity">
      <label>{{ $t("person.whatsappid") }}</label>
      <van-field
        v-model="form.whatsapp"
        ref="whatsapp"
        :border="false"
        :readonly="form.status == 2 || form.status == 3"
        @focus="focusWHATSAPP"
        @blur="blurWhatsapp"
        :placeholder="$t('update.whatsappLbel')"
      >
        <template #label>
          <div class="tel-label">
            +
            <span
              v-if="!form.whatsappCode"
              class="select-tel"
              @click="onshowPicker"
              >{{ $t("areaCode") }}</span
            >

            <van-field
              v-else
              ref="whatsappCode"
              v-model="form.whatsappCode"
              is-link
              readonly
              name="picker"
              @click="onshowPicker"
              class="select-tel"
            >
            </van-field>
          </div>
        </template>
      </van-field>

      <label>{{ $t("person.tel") }}</label>
      <van-field
        v-model="form.phonenumber"
        @focus="focusphone"
        @blur="blurphone"
        :readonly="form.status == 2 || form.status == 3"
        :border="false"
        :placeholder="$t('bind.telmsg')"
      >
        <template #label>
          <div class="tel-label">
            +
            <span
              v-if="!form.areaCode"
              class="select-tel"
              @click="onshowtelPicker"
              >{{ $t("areaCode") }}</span
            >
            <van-field
              v-else
              v-model="form.areaCode"
              is-link
              readonly
              name="picker"
              @click="onshowtelPicker"
              class="select-tel"
            >
            </van-field>
          </div>
        </template>
      </van-field>
      <div class="app-flex-bet">
        <div class="identity-width identity-width">
          <label>{{ $t("wallet.name") }}</label>
          <van-field
            v-model="form.name"
            border
            :readonly="form.status == 2 || form.status == 3"
            :placeholder="$t('wallet.actual')"
          />
        </div>
        <div class="identity-width">
          <label>{{ $t("wallet.surname") }}</label>
          <van-field
            v-model="form.surname"
            :readonly="form.status == 2 || form.status == 3"
            border
            :placeholder="$t('wallet.surname')"
          />
        </div>
      </div>

      <label>{{ $t("wallet.idNum") }}</label>
      <van-field
        v-model="form.idNumber"
        :readonly="form.status == 2 || form.status == 3"
        :border="false"
        :placeholder="$t('place') + $t('wallet.idNum')"
      />

      <label>{{ $t("wallet.idFront") }}</label>
      <div class="app-flex-bet">
        <van-uploader
          v-model="form.idFront"
          :readonly="form.status == 2 || form.status == 3"
          class="identity-width identity-top"
        >
          <img src="@/assets/images/id_icon.png" v-if="!form.idFront.length" />
          <div>
            {{ $t("wallet.front") }}
          </div>
        </van-uploader>
        <van-uploader
          v-model="form.idBack"
          class="identity-width identity-top"
          :readonly="form.status == 2 || form.status == 3"
        >
          <img src="@/assets/images/id_icon.png" v-if="!form.idBack.length" />
          <div>{{ $t("wallet.back") }}</div>
        </van-uploader>
      </div>

      <!-- <label>{{ $t("wallet.handleId") }}</label>
      <div>
        <van-uploader
          v-model="form.idRight"
          :readonly="form.status == 2 || form.status == 3"
          class="identity-width identity-top"
        >
          <img src="@/assets/images/id_right.png" v-if="!form.idRight.length" />
        </van-uploader>
      </div> -->
      <!-- :disabled="canSubMit()" -->
      <!-- <van-button round type="primary" :loading="loading" block @click="onSubmit" :disabled="canSubMit() || ID" class="identity-btn">{{ $t('sure') }}</van-button> -->
      <van-popup :show="showPicker" position="bottom">
        <van-picker
          :columns="columns"
          :columns-field-names="fieldName"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>
      <van-popup :show="showtelPicker" position="bottom">
        <van-picker
          :columns="telcolumns"
          :columns-field-names="fieldName"
          @confirm="onConfirmTel"
          @cancel="showtelPicker = false"
        />
      </van-popup>

      <van-button
        round
        type="primary"
        :loading="loading"
        block
        :disabled="form.status == 2 || form.status == 3"
        @click="onSubmit"
        class="identity-btn"
        >{{ $t("sure") }}</van-button
      >
      <br />
    </div>
  </div>
</template>
<script setup>
import { reactive, ref } from "@vue/reactivity";
import { onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { updateUserInfo, countryList } from "@/api/user";
import { useRouter, useRoute } from "vue-router";
import { onUpload } from "@/api/public";
import { addAuth, getAuthInfo, clearInfo, editAuth } from "@/api/card";
import { Toast } from "vant";
const { t } = useI18n();
const router = useRouter();
let showPicker = ref(false); //控制区号的显示
let showtelPicker = ref(false); //控制电话区号的显示
const telcolumns = []; //电话区号列表
const fieldName = { text: "areaCode", value: "areaCode" };
const columns = [{ areaCode: "234" }, { areaCode: "1" }]; //选择whats区号
const form = reactive({
  idFront: [],
  idBack: [],
  whatsapp: "",
  whatsappCode: "",
  areaCode: "",
  phonenumber: "",
  idNumber: "", // 证件号码
  name: "", // 名
  surname: "", // 姓
});
const encrytel = ref(null);
const encryWhatscode = ref(null);
const ID = ref(null);
const loading = ref(false);
//手机号码校验
const telvalidate = (value) => {
  const TEL_REGEXP = /^\d{7,11}$/;
  if (!TEL_REGEXP.test(value)) {
    return t("bind.telErr");
  } else {
    return false;
  }
};
//whatsapp校验
const whatsCodevalidate = (value) => {
  let testTeg1 = /^[7|8|9]{1}[0-9]{9,10}/;
  let tel = /^[0-9]{10,11}$/;
  if (!value) {
    return t("login.WHATSAPplace");
  } else if (value.length > 11 || value.length < 10) {
    return t("person.whatsappid") + t("two.whatsLength");
  } else if (
    (form.whatsappCode == 234 && !testTeg1.test(value)) ||
    !tel.test(value)
  ) {
    return t("person.whatsappid") + t("password.errFormat");
  } else {
    return false;
  }
};
//是否都有填写
function canSubMit() {
  let str = "";
  let bol = Object.keys(form).some((key) => {
    str = key;
    return (form[key] + "").length == 0;
  });
  if (bol) {
    console.log(str);
    let msg = "two." + str;
    Toast(t(msg));
  }
  return bol;
}
onMounted(() => {
  countryList().then((res) => {
    //获取电话区号
    console.log(res.data);
    Object.assign(telcolumns, res.data);
  });
});
const onConfirm = (item) => {
  console.log(item);
  form.whatsappCode = item.areaCode;
  showPicker.value = false;
};
const onConfirmTel = (item) => {
  console.log(item);
  form.areaCode = item.areaCode;
  showtelPicker.value = false;
};

async function onClear() {
  clearInfo();
}
async function onSubmit() {
  if (canSubMit()) {
    return;
  }
  console.log(canSubMit());
  if (whatsCodevalidate(encryWhatscode.value)) {
    Toast(whatsCodevalidate(form.whatsapp));
    return;
  } else if (telvalidate(encrytel.value)) {
    Toast(telvalidate(form.phonenumber));
    return;
  }
  let ret = await uploadAll();
  if (form.id) {
    editAuth({
      ...form,
      phonenumber: encrytel.value,
      whatsapp: encryWhatscode.value,
    })
      .then((res) => {
        loading.value = false;
        if (res.code == 200) {
          // ID.value = 1;
          Toast(t("person.identSucc"));
          router.back();
        }
      })
      .catch((err) => {
        loading.value = false;
      });
  } else {
    addAuth({
      ...form,
      phonenumber: encrytel.value,
      whatsapp: encryWhatscode.value,
    })
      .then((res) => {
        loading.value = false;
        if (res.code == 200) {
          // ID.value = 1;
          Toast(t("person.identSucc"));
        }
        router.back();
      })
      .catch((err) => {
        loading.value = false;
      });
  }
}
//获取焦点
function focusWHATSAPP() {
  console.log(form.whatsapp);
  if (form.status == 2 || form.status == 3) {
    return;
  } else {
    form.whatsapp = encryWhatscode.value;
  }
}
function onshowtelPicker() {
  if (form.status == 2 || form.status == 3) {
    return;
  } else {
    showtelPicker.value = true;
  }
}
function onshowPicker() {
  if (form.status == 2 || form.status == 3) {
    return;
  } else {
    showPicker.value = true;
  }
}
//获取焦点
function focusphone() {
  if (form.status == 2 || form.status == 3) {
    return;
  } else {
    form.phonenumber = encrytel.value;
  }
}
//失去焦点
function blurWhatsapp() {
  encryWhatscode.value = form.whatsapp;
  form.whatsapp = numberTel(encryWhatscode.value, 4);
}
function blurphone() {
  console.log(3333);
  encrytel.value = form.phonenumber;
  form.phonenumber = numberTel(encrytel.value, 4);
}
const numberTel = (value, num) => {
  var result = "";
  let end = value.length - num;
  if (value) {
    result = value.substring(0, 3) + "****" + value.substring(end);
  }
  return result;
};
function onUp(key) {
  let data = form[key][0] || "";
  if (data.file) return onUpload({ file: data.file });
  return form[key][0];
}
async function uploadAll() {
  loading.value = true;
  let ret = await Promise.all([
    onUp("idFront"),
    onUp("idBack"),
    // onUpload({ file: form.idFront[0].file }),
    // onUpload({ file: form.idBack[0].file }),
    // onUpload({ file: form.idRight[0].file }),
  ]).catch((err) => {
    loading.value = false;
  });
  form.certificateFrontUrl = ret[0].url;
  form.certificateBackUrl = ret[1].url;
  return ret;
}
getAuthInfo().then((res) => {
  console.log(res);
  if (res.code != 200 || !res.data) return;
  let user = JSON.parse(localStorage.getItem("user"));
  const {
    certificateFrontUrl,
    certificateBackUrl,
    idNumber,
    name,
    surname,
    id,
    status,
    whatsapp,
    whatsappCode,
    areaCode,
    phonenumber,
  } = res.data;
  certificateFrontUrl &&
    form.idFront.push({
      url: certificateFrontUrl,
    });
  certificateBackUrl &&
    form.idBack.push({
      url: certificateBackUrl,
    });
  form.idNumber = idNumber;
  form.name = name;
  form.surname = surname;
  form.id = id;
  form.status = status;
  ID.value = id;
  form.whatsapp = whatsapp;
  form.whatsappCode = whatsappCode;
  form.areaCode = areaCode;
  form.phonenumber = phonenumber;
  blurphone();
  blurWhatsapp();
});
// Promise.all(onUpload())
</script>
<style lang="less">
.identity {
  --van-cell-horizontal-padding: 0;
  height: calc(100vh - 90px);
  overflow: auto;
  label {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #000000;
    line-height: 1;
    padding-top: 13px;
    display: inline-block;
  }
  &-width {
    img,
    .van-uploader__preview-image {
      width: 161px;
      height: 95px;
      border-radius: 8px;
    }
    .van-uploader__preview-delete--shadow {
      border-radius: 10px;
      top: -5px;
    }
    .van-uploader__preview-delete-icon {
      transform: inherit;
    }
    .van-uploader__wrapper {
      display: block;
    }
  }
  &-width + &-width {
    margin-left: 10px;
  }
  &-top {
    margin-top: 10px;
    font-size: 13px;
    text-align: center;
  }
  &-btn {
    margin-top: 30px;
  }
  .tel-label {
    border-bottom: none;
    position: relative;
    top: -8px;

    text-align: center;
    display: flex;
    height: 32px;
    line-height: 40px;
    overflow: hidden;
    min-width: 100px;

    :deep(.van-cell.van-cell--clickable.van-field.select-tel) {
      height: 34px;
    }
    i.van-badge__wrapper.van-icon.van-icon-arrow.van-cell__right-icon {
      display: none;
    }
  }
  .van-cell.van-cell--clickable.van-field.select-tel {
    border: none;
  }
}
</style>
